package com.mobilous.client.tooltip;

import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.Widget;

public class TooltipListener implements MouseOverHandler,MouseOutHandler, Handler  {
	private static final int DEFAULT_OFFSET_X = 50;
	private static final int DEFAULT_OFFSET_Y = 50;

	private static class Tooltip extends PopupPanel {
		private int delay;

		public Tooltip(Widget sender, int offsetX, int offsetY, 
				final String text, final int delay, final String styleName) {
			super(true);

			this.delay = delay;

			HTML contents = new HTML(text);
			add(contents);

			int left = sender.getAbsoluteLeft() + offsetX;
			int top = sender.getAbsoluteTop() + offsetY;

			setPopupPosition(left, top);
			setStyleName(styleName);
		}

		public void show() {
			super.show();
			Timer t = new Timer() {
				public void run() {
					Tooltip.this.hide();
				}
			};
			t.schedule(delay);
		}
	}

	private Tooltip tooltip;
	private String text;
	private String styleName;
	private int delay;
	private int offsetX = DEFAULT_OFFSET_X;
	private int offsetY = DEFAULT_OFFSET_Y;
	private Widget widget;

	public TooltipListener(String text, int delay, String styleName, Widget widget) {
		this.widget=widget;
		this.text = text;
		this.delay = delay;
		this.styleName = styleName;
	}

	public void onMouseOver(MouseOverEvent event) {
		if (tooltip != null) {
			tooltip.hide();
		}
		tooltip = new Tooltip(this.widget, offsetX, offsetY, text, delay, styleName);
		tooltip.show();
	}

	public void onMouseOut(MouseOutEvent event) {
		tooltip.hide();
	}

	@Override
	public void onAttachOrDetach(AttachEvent event) {
		
	}
} 
